package com.xsf.jieyou.business.service;

import com.google.common.collect.Lists;
import com.xsf.jieyou.business.BusinessException;
import com.xsf.jieyou.business.common.dto.ResponseStatus;
import com.xsf.jieyou.provider.api.ProviderTbPermissionService;
import com.xsf.jieyou.provider.api.ProviderTbUserService;
import com.xsf.jieyou.provider.domain.TbPermission;
import com.xsf.jieyou.provider.domain.TbUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 自定义认证授权 实现类。
 * <p>
 * Description:TODO
 * </p>
 *
 * @author xsf
 * @version v1.0.0
 * @date 2019/11/14 0014 23:39
 * @see com.xsf.jieyou.business.service
 **/
@Component
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
    @Reference(version = "1.0.0")
    private ProviderTbUserService providerTbUserService;
    @Reference(version = "1.0.0")
    private ProviderTbPermissionService providerTbPermissionService;
    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 自定义认证授权
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 判断是否无密码方式登录,通过设置默认密码"12345678"完成登录认证
        String password = null;
        if (s.startsWith("#")) {
            // 无密码方式登录
            s = s.substring(1);
            password = this.passwordEncoder.encode("12345678");
        }

        // 1、用户名验证
        TbUser tbUser = this.providerTbUserService.get(s);

        // 用户不存在
        if (tbUser == null) {
            throw new BusinessException(ResponseStatus.ACCOUNT_NOT_EXIST);
        }
        // 用户已被封停
        if (tbUser.getStatus() == 0) {
            throw new BusinessException(ResponseStatus.ACCOUNT_SUSPENDED);
        }
        // 用户存在
        // 密码方式登录
        if (password == null) {
            password = tbUser.getPassword();
        } else {
            // 无密方式登录,标记#
            tbUser.setUsername("#" + tbUser.getUsername());
        }

        // 2、授予权限
        List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
        List<TbPermission> tbPermissions = this.providerTbPermissionService.selectByUserId(tbUser.getId());
        if (tbPermissions != null) {
            try {
                tbPermissions.forEach(tbPermission -> {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(tbPermission.getEnname());
                    grantedAuthorities.add(grantedAuthority);
                });
            } catch (Exception e) {
                log.warn("ID:" + tbUser.getId() + "USERNAME:" + tbUser.getUsername() + "--获取权限异常:" + e.toString());
            }
        }

        // 3、由框架完成认证工作
        return new User(tbUser.getUsername(), password, grantedAuthorities);
    }
}
